# -*- coding:utf-8 -*-
import traceback
from utils.logger import Md_Debug
from utils.db_utils import DbConn
from utils.backcode import ImportError


class Serialization(object):
    def __init__(self):
        self.db = DbConn()
    
    def commoit(self, body, params, null_params, sql):
        ret = {}
        try:
            data = self.serialize(body, params, null_params)
            if data[0] == None:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "%s is None" % data[1]
            else:
                # 获得序列化后的数据
                params = data[0]
                if self.db.commit(sql, params):
                    code = ImportError.IMPORT_CODE_SUCCESS
                    message = "success"
                else:
                    code = ImportError.COMMIT_SQL_ERROR
                    message = "database error"
        
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def query_list(self, body, params, null_params, sql):
        ret = {}
        try:
            data = self.serialize(body, params, null_params)
            if data[0] == None:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "%s is None" % data[1]
            else:
                # 获得序列化后的数据
                page = data[0][0]
                size = data[0][1]
                if len(data[0]) > 2:
                    data_list = self.db.fetch_all(sql, data[0][2:])
                else:
                    data_list = self.db.fetch_all(sql)
                if page and size:
                    data_list = self.paging(data_list, page, size)
                ret["response_data"] = data_list
                code = ImportError.IMPORT_CODE_SUCCESS
                message = "success"
        
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def query_info(self, body, params, null_params, sql):
        """查询单个"""
        ret = {}
        try:
            data = self.serialize(body, params, null_params)
            if data[0] == None:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "%s is None" % data[1]
            else:
                # 获得序列化后的数据
                params = data[0]
                data_list = self.db.fetch_one(sql, params)
                ret["response_data"] = data_list
                code = ImportError.IMPORT_CODE_SUCCESS
                message = "success"
        
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def serialize(self, body, params, null_params=None):
        """
        :param body: 请求体
        :param params: 需要解析的参数
        :return: 如果成功返回解析的[数据,空字符],如果不成功返回[None,错误的字段]
        """
        data = []
        for param in params:
            value = body.get(param, None)
            data.append(value)
            if (value == None):
                if null_params != None:
                    if param not in null_params:
                        return [None, param]
                else:
                    return [None, param]
        return [data, ""]
    
    def paging(self, data_list, page, size):
        """分页"""
        ret = {
            'page': page, 'size': size, 'total_page': 0, 'total_size': 0
        }
        total_size = len(data_list)
        if total_size % size == 0:
            total_page = total_size / size
        else:
            total_page = total_size / size + 1
        start_index = (page - 1) * size
        end_index = page * size
        
        ret['total_page'] = total_page
        ret['total_size'] = total_size
        if end_index > len(data_list):
            ret['data'] = data_list[start_index:]
        else:
            ret['data'] = data_list[start_index: end_index]
        return ret
